package org.geektimes.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: ResponseHandlerUtil
 * @Description: 应答处理工具了
 * @Author: MaWenHao
 * @Created: 2021/2/28 - 下午11:29
 */
public final class ResponseHandlerUtil {
    
    public static void responseJsonHandle(Object obj, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonStr = JSONUtil.toJsonStr(obj);
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().write(jsonStr);
    }

    /**
     * forward
     * @param obj forward的页面名称
     * @param request
     * @param response
     */
    public static void responsePageHandle(Object obj, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String viewPath = StrUtil.toString(obj);
        if (viewPath.startsWith("froward:")) {
            viewPath = viewPath.substring("forward:".length()).trim();
            if (!viewPath.startsWith("/")) {
                viewPath = "/" + viewPath;
            }
            RequestDispatcher requestDispatcher = request.getRequestDispatcher(viewPath);
            requestDispatcher.forward(request, response);
            return;
        }
        viewPath = viewPath.substring("redirect:".length()).trim();
        if (!viewPath.startsWith("/")) {
            viewPath = "/" + viewPath;
        }
        response.sendRedirect(viewPath);

    }
}
